//
//  KPHomeViewModel.swift
//  Alamofire
//
//  Created by Daiyi on 2024/4/20.
//
import Foundation
import DDBase
import KPAppKit

class KPHomeViewModel: DDBaseViewModel<KPOrderModel> {
    
    private(set) var orderList:[DDItemModel<KPOrderModel>] = []
    
    override func loadHeaderData() {
        Single.zip(self.loadOrder(), self.loadProduct())
            .subscribe(onSuccess: { [weak self] value in
                guard let self = self, let delegate = self.delegate else {return}
                if (!value.0 && !value.1) {
                    delegate.loadComplete(self, code: DDNetworkError.Code.business, message: "Network Anomaly")
                } else {
                    delegate.loadComplete(self, code: 200, message: nil)
                }
            }, onFailure: { [weak self] error in
                guard let self = self, let delegate = self.delegate else {return}
                delegate.loadComplete(self, code: DDNetworkError.Code.netErr, message: error.localizedDescription)
            }).disposed(by: self.disposeBag)
    }

    
    private func loadOrder() -> Single<Bool> {
        DDNetworkManager.provider.dd.request(HomeNetType.getOrderInfo)
            .mapToJSON()
            .map { json in
                let size = CGSize(width: 90, height: 106)
                self.orderList = json["data"].arrayValue.compactMap {
                    let order = KPOrderModel(jsonData: $0)
                    if order.isFaied {
                        return nil
                    }
                    let item = DDItemModel(order, cellId: self.cellId, cellSize: size, addEvents: self.events)
                    
                    return item
                }
                return true
            }.catchAndReturn(false)
    }
    
    private func loadProduct() -> Single<Bool> {
        let request = HomeNetType.getProducts(["phoneNumber": KPUser.shared.phoneNumber])
        return DDNetworkManager.provider.dd.request(request)
            .mapToJSON()
            .map { json in
                self.handlerData(json, target: request)
                return true
            }.catchAndReturn(false)
    }
    
    deinit {
        Log.d("KPHomeViewModel deinit")
    }
}
